import datetime

from google.appengine.ext import db

import datamodel
import tvweb
import bot

def store_serie(serie, user):
    users = db.GqlQuery('SELECT * FROM User WHERE userProp = :userName AND serie = :serieTitle', 
                    userName=user, serieTitle=serie)
    series = db.GqlQuery('SELECT * FROM Serie WHERE title = :title', title=serie)
    save = True
    if series.count() == 0 and save:
        save = tvweb.obtain_episodes_list(serie)
        if save:
            dbSerie = datamodel.Serie()
            dbSerie.title = serie
            dbSerie.put()
    if users.count() == 0 and save:
        dbUser = datamodel.User()
        dbUser.userProp = user
        dbUser.serie = serie
        dbUser.put()
    else:
        save = False
    return save
    
def remove_serie(user, serie):
    users = db.GqlQuery('SELECT * FROM User WHERE userProp = :userName AND serie = :serieTitle', 
                    userName=user, serieTitle=serie)
    users[0].delete()
    
def restore_series(user):
    series = db.GqlQuery('SELECT * FROM User WHERE userProp = :userName ORDER BY serie ASC', userName=user)
    seriesList = [serie.serie for serie in series]
    return seriesList

def store_calendar(calendar):
    try:
        db.put(calendar)
    except:
        return False
    return True

def restore_calendar(user, serie):
    seriesList = db.GqlQuery('SELECT * FROM User WHERE userProp = :userName AND serie = :userSerie ORDER BY serie ASC', 
                        userName=user, userSerie=serie)
    seriesList = [serie.serie for serie in seriesList]
    calendar = datamodel.Calendar.all()
    calendar.filter('serie IN', seriesList)
    calendar.order('date')
    return calendar
    
def restore_calendar_by_serie(serie):
    calendar = datamodel.Calendar.all()
    calendar.filter('serie =', serie)
    return calendar
    
def restore_calendar_by_date(user, date):
    seriesList = db.GqlQuery('SELECT * FROM User WHERE userProp = :userName ORDER BY serie ASC', 
                        userName=user)
    seriesList = [serie.serie for serie in seriesList]
    calendar = datamodel.Calendar.all()
    calendar.filter('date =', date)
    calendar.filter('serie IN', seriesList)
    return calendar

def search_today_episodes(user):
    date = datetime.date.today()
    return restore_calendar_by_date(user, date)
    
def check_next_episode(user, serie):
    date = datetime.date.today()
    calendar = datamodel.Calendar.all()
    calendar.filter('serie =', serie)
    calendar.filter('date >', date)
    calendar.order('date')
    return calendar

def save_preferences(user, noti, direc, host, format):
    preference = datamodel.Preferences()
    try:
        pref = datamodel.Preferences.all()
        pref.filter('userId =', user)
        preference = pref[0]
    except:
        preference.userId = user
    preference.notify = noti
    preference.direct = direc
    preference.hosting = host
    preference.formats = format
    preference.put()

def load_preferences(user):
    pref = datamodel.Preferences.all()
    pref.filter('userId =', user)
    return pref

def obtain_users_to_notify():
    users = datamodel.Preferences.all()
    users.filter('notify =', True)
    return users

def obtain_actual_users():
    users = datamodel.User.all()
    users.order('userProp')
    actual = []
    for user in users:
        if user.userProp.nickname() not in actual:
            actual.append(user.userProp.nickname())
    return actual

def obtain_list_series():
    seriesList = datamodel.Serie.all()
    series = []
    for serie in seriesList:
        if serie.title not in series:
            series.append(serie.title)
    return series

def obtain_downloads_model(serie, direct=False, host='All', format='all'):
    try:
        query = datamodel.Downloads.all()
        query.filter('serie =', serie)
        query.filter('direct =', direct)
        if direct:
            query.filter('hosting =', host)
            query.filter('format =', format)
        if query.count() > 0:
            return query[0]
    except:
        return None

def store_download(serie, links, direct=False, hosting='All', format='all', source=''):
    down = datamodel.Downloads()
    down.serie = serie
    down.direct = direct
    down.hosting = hosting
    down.format = format
    down.links = links
    down.source = source
    down.date = datetime.date.today()
    down.put()
    return down

def delete_old_downloads():
    date = datetime.date.today()
    dif = datetime.timedelta(days=2)
    date = date - dif
    q = db.GqlQuery("SELECT * FROM Downloads WHERE date < :1", date)
    results = q.fetch()
    db.delete(results)

def store_design(user, theme, layout):
    design = datamodel.Design()
    try:
        des = datamodel.Design.all()
        des.filter('userId =', user)
        design = des[0]
    except:
        design.userId = user
    design.theme = theme
    design.layout = layout
    design.put()

def load_design(user):
    des = datamodel.Design.all()
    des.filter('userId =', user)
    return des

def series_without_episodes():
    cals = datamodel.Calendar.all()
    actualSeries = []
    for cal in cals:
        if cal.serie not in actualSeries:
            actualSeries.append(cal.serie)
    seriesList = obtain_list_series()
    return [s for s in seriesList if s not in actualSeries]

def delete_old_episodes():
    date = datetime.date.today()
    dif = datetime.timedelta(days=365)
    date = date - dif
    q = db.GqlQuery("SELECT * FROM Calendar WHERE date < :1", date)
    results = q.fetch()
    db.delete(results)

def find_series_refresh_incomplete():
    cals = datamodel.Calendar.all()
    actualSeries = []
    for cal in cals:
        if cal.serie not in actualSeries:
            actualSeries.append(cal.serie)
    seriesList = obtain_list_series()
    series = [s for s in seriesList if s not in actualSeries]

    cals = datamodel.Calendar.all()
    cals.filter('episode =', 'TBA')
    for cal in cals:
        if cal.serie not in series:
            series.append(cal.serie)
    return series

def find_series_refresh():
    date = datetime.date.today()
    cals = datamodel.Calendar.all()
    cals.order('-nroEp')
    serie = ''
    update = []
    for cal in cals:
        if cal.serie != serie:
            serie = cal.serie
            if cal.date < date:
                update.append(cal.serie)
    return update
